/**
 * @title 非标类产品分析报告
 */
import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Tabs, message } from 'antd';
import { ContentPackage, DATA_ENTRY, AdvancedSearch, NoQueryC } from '../../../comps';
import TabPage from './components/tabPage';
import styles from './index.less';
import AssetReport from './assetReport';

const { TabPane } = Tabs;

@connect(({ loading, productAGroupM }) => ({ loading, productAGroupM }))
export default class index extends PureComponent {
  state = {
    tabList: [],
    activeKey: undefined,
    selectNodes: [], // 选中的项
  };
  // 查询
  onQuery = (_data) => {
    const { tabList } = this.state;
    if (!_data.productList?.length) {
      message.warning('请选择产品后查询！');
      return;
    }
    // tabList
    let newTabList = this.combineSelection(_data.productList);
    if (!!tabList.length) {
      newTabList.forEach((item) => {
        let tempIndex = tabList.findIndex((tab) => item.key === tab.key);
        if (tempIndex !== -1) {
          tabList.splice(tempIndex, 1);
        }
      });
    }
    this.setState({
      tabList: this.state.isReset ? [...newTabList] : [...tabList, ...newTabList],
      isReset: false,
    });
  };
  // 清除
  onClear = () => {
    this.setState({
      isReset: true,
    });
  };
  // 寻找父级节点
  findParent = (targetKey, children) => {
    let result = false;
    children.forEach((child) => {
      if (child.key === targetKey) {
        result = true;
      } else {
        if (!result && child.children && child.children?.length) {
          result = this.findParent(targetKey, child.children);
        }
      }
    });
    return result;
  };
  // 获取组合code
  getGroupCode = (target) => {
    const { selectNodes } = this.state;
    return selectNodes.filter((item) => item.key === target)[0]?.portfolioCode;
  };
  // 组合结果
  combineSelection = (selectTreeData) => {
    const {
      productAGroupM: { productGroup },
    } = this.props;
    let tempTabList = [];
    for (let len = selectTreeData.length, i = 0; i < len; i++) {
      let tempTarget = selectTreeData[i]; // 暂存目标key
      let parentIndex = productGroup.findIndex((item) => item.key === tempTarget);
      if (parentIndex > -1) {
        // 如果选中是产品
        let tempPro = productGroup[parentIndex];
        let tempIndex = tempTabList.findIndex((item) => item.key === tempPro.key);
        if (tempIndex > -1) {
          // 已记录到缓存
          tempTabList[tempIndex].productId = tempPro.portfolioCode;
          if (Array.isArray(tempTabList[tempIndex]?.groupList) && !tempTabList[tempIndex]?.groupList.includes(tempPro.portfolioCode)) {
            tempTabList[tempIndex]?.groupList.push(tempPro.portfolioCode);
          }
        } else {
          tempTabList.push({
            // 未记录到缓存
            key: tempPro.key,
            portfolioName: tempPro.portfolioName,
            portfolioCode: tempPro.portfolioCode,
            productId: tempPro.portfolioCode,
            groupList: [tempPro.portfolioCode],
          });
        }
      } else {
        // 不是产品
        // 1、找到第一父级产品
        let parentObj = undefined;
        productGroup.forEach((item) => {
          if (item.children && item.children?.length > 0 && this.findParent(tempTarget, item.children)) {
            parentObj = item;
          }
        });
        // 2、将父级记录到缓存, 并记录组合到结果
        let tempIndex = tempTabList.findIndex((item) => item.key === parentObj.key);
        if (tempIndex == -1 && parentObj) {
          // 未记录到缓存
          tempTabList.push({
            key: parentObj.key,
            portfolioName: parentObj.portfolioName,
            portfolioCode: parentObj.portfolioCode,
            productId: undefined,
            groupList: [this.getGroupCode(tempTarget)],
          });
        } else {
          // 已记录到缓存
          tempTabList[tempIndex].groupList.push(this.getGroupCode(tempTarget));
        }
      }
    }
    return tempTabList;
  };
  // 选中
  treeSelectChange = (val) => {
    this.setState({
      selectNodes: val?.info || [],
    });
  };
  //删除
  changeTabList = (arr = []) => {
    this.setState({
      tabList: [...arr],
    });
  };

  render() {
    const { tabList } = this.state;
    const searchProps = {
      dataSource: [
        {
          dataIndex: 'productList',
          title: '产品名称',
          type: DATA_ENTRY.PRODUCTGROUPTREE,
          onChange: this.treeSelectChange,
          placeholder: '请选择产品',
          multiple: true,
          allowClear: true,
        },
      ],
      onRef: (ref) => (this.searchRef = ref),
      onQuery: this.onQuery,
      onClear: this.onClear,
    };
    return (
      <ContentPackage
        title='非标类产品分析报告'
        contentHtml={
          <div className={styles.nonstardReportCont}>
            <AdvancedSearch {...searchProps} />
            {tabList && tabList.length ? (
              <AssetReport tabList={tabList} type='main' changeTabList={this.changeTabList} />
            ) : (
              <div style={{ marginTop: '10px' }}>
                <NoQueryC />
              </div>
            )}
          </div>
        }
      />
    );
  }
}
